/**
 * @flow
 */

import React, {useEffect} from 'react'

// prettier-ignore
import {
  SafeAreaView,
  StyleSheet,
  BackHandler,
  View
} from 'react-native'

import PPC from './RxPageConfig'
import PlatformUtil from '../../commons/utils/PlatformUtil'

const RxPageCore = props => {
  const children = props.children || null
  const navigation = props.navigation || null
  // console.log('RxPageCore-> props=', props)
  // console.log('RxPageCore-> children=', children)
  // console.log('RxPageCore-> navigation=', navigation)
  const nav = () => {
    const n = navigation || null
    return n
  }
  // const navParams = () => {
  //   const n = nav || null
  //   if (!n) return {}
  //   const s = n.state || {}
  //   const p = s.params || {}
  //   return p
  // }

  const goBack = () => {
    nav.goBack
    // https://www.reactnative.dev/docs/backhandler
    return true
  }
  // prettier-ignore
  const t = {appear: null, disappear: null, goBack: null, pageDidAppear: null, pageDidDisAppear: null}
  useEffect(() => {
    if (nav && typeof nav === 'object') {
      t.appear = nav.addListener('didFocus', t.pageDidAppear)
      t.disappear = nav.addListener('didBlur', t.pageDidDisAppear)
    }
    if (PlatformUtil.isAndroid()) {
      BackHandler.addEventListener('hardwareBackPress', goBack)
    }
  }, [t])

  t.pageDidAppear = () => {
    // -- common code
  }

  t.pageDidDisAppear = () => {
    // -- common code
  }

  t.goBack = () => {
    // console.log('点击返回')
    goBack()
  }

  const p = props || {}
  const navBar = p.navBar
  const style = p.style || {}

  return (
    <SafeAreaView style={[style, styles.container]}>
      {navBar}
      <View style={styles.pageContainer}>{children}</View>
    </SafeAreaView>
  )
}

RxPageCore.prototype = PPC.pageCore.prototype
RxPageCore.defaultProps = PPC.pageCore.defaultProps
export default RxPageCore

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  pageContainer: {
    flex: 1,
  },
})
